package com.atguigu.gmall.realtime.util;

import com.atguigu.gmall.realtime.bean.OrderInfo;
import org.apache.commons.beanutils.BeanUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author lzc
 * @Date 2022/4/17 14:36
 */
public class JdbcUtil {
    public static Connection getJdbcConnection(String driver, String url, String user,
                                               String password) throws ClassNotFoundException, SQLException {
        // 加载驱动
        Class.forName(driver);
        
        
        return DriverManager.getConnection(url, user, password);
    }
    
    public static void main(String[] args) throws Exception {
        
//        Connection conn = getJdbcConnection(Constant.PHOENIX_DRIVER, Constant.PHOENIX_URL, null, null);
        Connection conn = getJdbcConnection("com.mysql.cj.jdbc.Driver", "jdbc:mysql://hadoop162:3306/gmall2022?useSSL=false", "root", "aaaaaa");
//        List<JSONObject> list = queryList(conn, "select * from dim_user_info where id=?", new Object[]{"3612"}, JSONObject.class);
//        List<JSONObject> list = queryList(conn, "select * from order_info", new Object[]{}, JSONObject.class);
        List<OrderInfo> list = queryList(conn, "select * from order_info", new Object[]{}, OrderInfo.class);
        for (OrderInfo obj : list) {
            System.out.println(obj);
        }
        
    }
    
    // 查询数据库, 返回多行多列
    // select .. from .. where id=? and a=?
    public static <T> List<T> queryList(Connection conn, String sql, Object[] args, Class<T> tClass) throws Exception {
        ArrayList<T> result = new ArrayList<>();
        
        PreparedStatement ps = conn.prepareStatement(sql);
        // 给sql中的占位符赋值
        for (int i = 0; i < args.length; i++) {
            Object arg = args[i];
            ps.setObject(i + 1, arg);
        }
        // 执行查询sql, 返回值是结果集
        ResultSet resultSet = ps.executeQuery();
        ResultSetMetaData metaData = resultSet.getMetaData(); // 查询的结果元数据
        int columnCount = metaData.getColumnCount();  // 获取列的数量
        
        while (resultSet.next()) { // 移动指针到行上
            // 获取到一行数据, 封装到一个 T类型的对象
            T t = tClass.newInstance();  // 使用反射创建T类型的对象, 利用的无参构造器
            // 获取到这一行的每一列  务必加等号
            for (int i = 1; i <= columnCount; i++) {
                // 表中的列名,和T中的属性名应该完全一致
                String name = metaData.getColumnLabel(i);
                Object v = resultSet.getObject(i);
                
                BeanUtils.setProperty(t, name, v);
            }
            
            result.add(t);
        }
        
        
        return result;
    }
}
